package cn.com.dreamtouch.magicbox_common.util;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;

/**
 * 网络监控广播
 * Created by MuHan on 15/12/16.
 */
public class NetworkChangeReceiver extends BroadcastReceiver {
   public OnNetworkChangeListener  mListener ;
    public boolean firstCheck=true;
    public boolean lastHasNetwork=false;
    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isAvailable()) {
            int networkType = networkInfo.getType();
            boolean isWifi;
            if(networkType == ConnectivityManager.TYPE_WIFI)
                isWifi=true;
            else
                isWifi=false;

            if(mListener!=null)
            {
                mListener.onNetworkChanged(context,isWifi,true);
            }
           else {
                Log.i("NetworkChangeReceiver", networkInfo.getTypeName() + "已连接");
                if(!firstCheck&!lastHasNetwork)//第一次不显示已联网状态并且上次为网络已断开
                Toast.makeText(context.getApplicationContext(),"网络已连接", Toast.LENGTH_LONG).show();
            }
            lastHasNetwork=true;
        } else {
            lastHasNetwork=false;
            if(mListener!=null)
            {
                mListener.onNetworkChanged(context,false,false);
            }
            else {
                Log.i("NetworkChangeReceiver","网络已断开");
                Toast.makeText(context.getApplicationContext(), "网络已断开", Toast.LENGTH_LONG).show();
            }
        }
        firstCheck=false;
    }
    public interface OnNetworkChangeListener {
        public void onNetworkChanged(Context context, boolean hasWifi, boolean isAvailable);

    }
   public  void register( Context context)
    {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        context.registerReceiver(this, intentFilter);
    }
    public void unregister ( Context context)
    {
        context.unregisterReceiver(this);
    }
}
